package assignment3;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import util.EasyInput;


public class DataMinePanel extends JPanel {

	private JButton open;
	private JTextArea text;

	ArrayList<String> lst = new ArrayList<String>();

	ArrayList<String> lst2 = new ArrayList<String>();

	public DataMinePanel() {
		this.setLayout(new BorderLayout());

		text = new JTextArea(10, 10);
		text.setLineWrap(true);
		text.setEditable(false);
		JScrollPane scrollPane = new JScrollPane(text);
		this.add(scrollPane);
		
		open = new JButton("Load File");
		open.addActionListener(new OpenFileListener());
		JPanel openPanel = new JPanel();
		openPanel.add(open);

		this.add(scrollPane, BorderLayout.CENTER);
		this.add(open, BorderLayout.SOUTH);
	}

	private class OpenFileListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			String fname = EasyInput.chooseFile();
			File file = new File(fname);
			ScanFile(file);
			text.setText("There are " + numbaskets(lst) + " baskets\nThe number of " +
					"non-distinct items is " + 
					repitems(lst) + " \n" +"The average length" +
							" of the baskets is " + average(lst) + " items\n" +
							"There are " + nonrepitems(lst) + " unique items\n");
		}
	}

	public void ScanFile(File file) {
		try {
			Scanner sc = new Scanner(file);
			while (sc.hasNextLine()) {
				String line = sc.nextLine();
				lst.add(line);
			}
		} catch (IOException e) {
			System.out.println("I/O error: " + e);
		}
	}

	public double average(ArrayList<String> lst) {
		double x = 0;
		for (int i = 0; i < lst.size(); ++i) {
			Scanner sc1 = new Scanner(lst.get(i));
			while (sc1.hasNext()) {
				if (sc1.next() == " ") {
					x += 0;
				} else {
					x += 1;
				}
			}
		}
		return (x / (lst.size()));
	}
	
	public int repitems(ArrayList<String> lst) {
		int b = 0;
		for (int i = 0; i < lst.size(); ++i) {
			Scanner sc1 = new Scanner(lst.get(i));
			while (sc1.hasNext()) {
				if (sc1.next() == " ") {
					b += 0;
				} else {
					b += 1;
				}
			}
		}
		return b;
	}
	
	public int nonrepitems(ArrayList<String> lst) {
		int z = 0;
		for (int c = 0; c < lst.size(); ++c) {
			Scanner sc2 = new Scanner(lst.get(c));
			while (sc2.hasNext()) {
				String q = sc2.next();
				if (lst2.contains(q)) {
					z += 0;
					lst2.add(q);
				} else {
					z += 1;
					lst2.add(q);
				}
			}
		}
		return z;
	}
	
	public int numbaskets(ArrayList<String> lst) {
		return (lst.size() - 1);
	}
}
